package com.dennytech.tac.utils.db;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.dennytech.tac.model.Record;

public class TimelineDBHelper extends DBHelper<Record> {

	private static TimelineDBHelper instance;

	public static TimelineDBHelper instance() {
		return instance;
	}

	public static void init(Context c) {
		if (instance == null) {
			instance = new TimelineDBHelper(c);
		}
	}

	public TimelineDBHelper(Context c) {
		super(c, "tl");
	}

	@Override
	protected SQLiteDatabase createDataBase(Context c) throws IOException {
		File path = new File(dbDir(c), dbName());
		SQLiteDatabase db = null;
		try {
			db = SQLiteDatabase.openOrCreateDatabase(path, null);
		} catch (Exception e) {
			return null;
		}

		StringBuilder sb = new StringBuilder();
		sb.append("CREATE TABLE IF NOT EXISTS ").append(tableName).append(" (");
		sb.append("id INTEGER PRIMARY KEY AUTOINCREMENT, ");
		sb.append("image TEXT, ");
		sb.append("intro TEXT, ");
		sb.append("date TEXT);");

		db.execSQL(sb.toString());
		return db;
	}

	@Override
	protected String dbName() {
		return "tl.db";
	}

	@Override
	protected File dbDir(Context c) {
		return c.getDir("database", Context.MODE_PRIVATE);
	}

	@Override
	public List<Record> query() {
		List<Record> list = new ArrayList<Record>();
		try {
			String query = "SELECT * FROM " + tableName + " ORDER BY id desc;";
			Cursor c = db.rawQuery(query, null);
			if (c.moveToFirst()) {
				do {
					Record r = new Record();
					r.setId(c.getInt(0));
					r.setImage(c.getString(1));
					r.setIntro(c.getString(2));
					r.setDateStr(c.getString(3));
					list.add(r);

				} while (c.moveToNext());
				c.close();
			} else {
				c.close();
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		return list;
	}

	@Override
	public void insert(Record t) {
		ContentValues cv = new ContentValues();
		cv.put("image", t.getImage());
		cv.put("intro", t.getIntro());
		cv.put("date", t.getDateStr());
		db.insert(tableName, null, cv);
	}

	@Override
	public int delete(Record t) {
		return db.delete(tableName, "id = " + t.getId(), null);
	}

	@Override
	public int update(Record t) {
		ContentValues cv = new ContentValues();
		cv.put("intro", t.getIntro());
		return db.update(tableName, cv, "id = " + t.getId(), null);
	}

}
